/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package com.crmapi.service.impl;

import com.armapi.utlis.CreateUUID;
import com.crmapi.exceptiion.BusinessException;
import com.crmapi.mapper.ApprovalMapper;
import com.crmapi.mapper.ContractMapper;
import com.crmapi.pojo.*;
import com.crmapi.service.ContractService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.UUID;

/**
 * <p>Project: CRMSystem - ContractServiceImpl</p>
 * <p>Powered by yzc On 2023-11-28 15:08:10</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */
@Service
public class ContractServiceImpl implements ContractService {

    @Autowired
    ContractMapper contractMapper;

    @Autowired
    ApprovalMapper approvalMapper;

    //保存合同，同时批量保存附件和回款计划
   @Transactional
    @Override
    public int save(Contract contract) {
        contract.setId(CreateUUID.getUUid());
        List<Attachment> attachmentList = contract.getAttachmentList();
        attachmentList.forEach(attachment -> {
            //拿到客户id
            attachment.setCid(contract.getCustomerId());
            //拿到合同id
            attachment.setContractId(contract.getId());
        });
        contractMapper.saveAttachment(attachmentList);
        List<Plan> planList = contract.getPlanList();
        planList.forEach(plan -> {
            //拿到合同id
            plan.setContractId(contract.getId());
            //计算是否逾期
            plan.setDay(getDays(plan.getPlanTime()));
            //计算回款率
            plan.setRatio(getRatio(contract.getAmount(),contract.getPayment(), plan.getAmount()));
        });
        contractMapper.savePlan(planList);
       int rs = contractMapper.save(contract);
       if (rs == 0)
           return rs;
       //查询审核流程、抄送人
       ApprovalProcess approvalProcess = approvalMapper.queryByType(1);
       String mid = CreateUUID.getUUid();
       //保存审核表
       Approval approval = new Approval();
       approval.setId(mid);
       approval.setCode(getMAXCode());
       approval.setType(1);
       approval.setBid(contract.getCustomerId());
       approval.setApplicant(contract.getUser());
       approval.setApprover(approvalProcess.getApprover());
       approval.setApproverId(approvalProcess.getApproverId());
        rs = approvalMapper.save(approval);
       if (rs ==0)
          throw new BusinessException("审批表保存失败");
       //插入抄送人记录
       rs =  approvalMapper.saveReciver(mid,approvalProcess.getReciverList());
       if (rs == 0)
           throw  new BusinessException("合同抄送人保存失败");
       return 1;
    }

    //条件分页查询
    @Override
    public PageBean queryContract(Integer page, Integer pageSize, String code, String name, String customerName,
                                  Integer status, String contractTime,Integer type,String userCode) {
        PageHelper.startPage(page,pageSize);
        List<Contract> contractList = contractMapper.queryContract(code, name, customerName, status, contractTime,
                type,userCode);
        PageInfo pageInfo = new PageInfo<>(contractList);
        return new PageBean(pageInfo.getTotal(),contractList);
    }

    @Override
    public int del(List<String> ids) {
        return contractMapper.del(ids);
    }


    //判断是否逾期  没有逾期——————距离还款还有多少天，逾期—————————逾期多少天
    String getDays(String date){
        LocalDate dueDate = LocalDate.parse(date);
        LocalDate currentDate = LocalDate.now();
        if (currentDate.isBefore(dueDate)) {
            long daysLeft = ChronoUnit.DAYS.between(currentDate, dueDate);
            return "距还款日 " + daysLeft + " 天";
        } else if (currentDate.isAfter(dueDate)) {
            long daysLate = ChronoUnit.DAYS.between(dueDate, currentDate);
            return "已经逾期 " + daysLate + " 天";
        } else {
            return "今天是还款日";
        }
    }

    //回款比率  ===》  （回款金额/(总应回款金额-预付款金额）*100
    String getRatio(Double amount,Double payment,Double payback){
        //需要还款的金额
        double v = amount - payment;
        double ratio = payback / v * 100;
        // 保留两位小数并四舍五入，然后将其转换为字符串
        return String.format("%.2f%%", ratio);
    }

    //查询审核表最大的code
    public String  getMAXCode(){
        String MAXcode = approvalMapper.queryCode();
        String newCode = null;
        if (MAXcode == null){
            //说明没有编号，生成初始编号
            newCode="SHBH-00001";
        }else {
            String[] splitResult = MAXcode.split("-"); //分割字符串
            String prefix = splitResult[0]; //前缀
            String suffix =String.valueOf(Integer.parseInt(splitResult[1]) + 1) ; //后缀加1
            newCode = prefix +"-"+suffix; //拼接前缀和后缀
        }
        return newCode;
    }
}
